import React, {useRef, useState, useEffect} from 'react';
import GoBack from "@/components/TheGoBack";
import {useLocation, useNavigate} from 'react-router-dom';
import {
    ProForm,
    ProFormCheckbox,
    ProFormDateTimePicker,
    ProFormDateTimeRangePicker,
    ProFormSelect,
    ProFormText
} from '@ant-design/pro-components';
import {Col, message, Row, Space} from "antd";
import Goods from "../goods/index.jsx";
import moment from "moment";
import {
    apiSeckillActivityAdd,
    apiSeckillActivityEdit,
    apiSeckillActivityDetail,
    apiSeckillActivitySkuFloorPriceVerify
} from "@/api/marketingTool/kill.js";
import {apiGetStoreInfo} from "@/api/couponManagement/couponsList.js";
import Decimal from "decimal.js";

const Add = () => {
    const navigate = useNavigate()
    const location = useLocation();
    const formRef = useRef();
    const format = "YYYY-MM-DD HH:mm";
    const mode = location.state.mode;
    const activityId= location.state.activityId
    const [isProprietary, setIsProprietary] = useState()
    let title = null
    switch (mode) {
        case 'add':
            title = "创建活动";
            break;
        case 'edit':
            title = "编辑活动";
            break;
        case 'view':
            title = "活动详情";
            break;
        default:
            break;
    }
    const [options, setOptions] = useState([
        {
            value: 'SECKILL_HOMEPAGE',
            label: '首页秒杀',
        },
        {
            value: 'SECKILL_ACTIVITY',
            label: '活动秒杀',
        },
    ])

    useEffect(() => {
        getShopInfo()
    }, [])
    const getShopInfo = async () => {
        await apiGetStoreInfo().then(res => {
            if (res.code === 0) {
                setIsProprietary(res.data.isProprietary)
                if (res.data.isProprietary === "N") {
                    setOptions([{value: 'SECKILL_ACTIVITY', label: '活动秒杀',}])
                }
            }
        })
    }
    // 将数据转成表格格式
    const convertData = (data) => {
        // console.log(data)
        return data.map((item, index) => {
            return {
                key: index,
                killSort: item.sort,
                goodsId: item.goodsId,
                goodsName: item.goodsName,
                skuInfoVos: item.skuList.map((sku, index) => {
                    return {
                        "materialId": sku.materialId,//物料编码
                        "goodsSkuId": sku.skuId,//skuId
                        "isJoin": 0,
                        skuAttributes: sku.skuAttributes || [],
                        skuStock: sku.skuStock,
                        "a_stock": sku.activityStock,//活动库存
                        skuCurrentPrice: sku.skuCurrentPrice,
                        "a_price": sku.activityGoodsSkuPrice ? Decimal(sku.activityGoodsSkuPrice ?? 0).div(Decimal(100)).toNumber() : 0,//活动价格
                        'isLimit': sku.quota === -1 ? 0 : 1,
                        "quota_count": sku.quota !== -1 ? sku.quota : mode !== 'view' ? null : -1,
                        "virtualCount": sku.virtualNum,//虚拟抢购件数
                        goodsBuySum: sku.goodsBuySum,
                        goodsSurplusSum: sku.goodsSurplusSum,
                        "activityStock_copy": sku.activityStock
                    }
                })
            }
        })
    }
    const transData = (data) => {
        // console.log(data)
        return data.map(item => {
            return {
                "goodsId": item.goodsId,//商品id
                "goodsName": item.goodsName,//商品名称
                "sort": item.killSort,//排序
                "skuList": item.skuInfoVos.map(sku => {
                    let t = {
                        "materialId": sku.materialId,//物料编码
                        "skuId": sku.goodsSkuId,//skuId
                        skuAttributes: sku.skuAttributes,
                        "skuEnabled": 1,//是否参与活动 0不参加  1参加
                        "activityStock": sku.a_stock,//活动库存
                        "activityGoodsSkuPrice": sku.a_price ? sku.a_price * 100 : 0,//活动价格
                        "quota": sku.hasOwnProperty('isLimit') && sku.isLimit ? sku.quota_count : -1,//-1不限购 限购
                        "virtualNum": sku.virtualCount,//虚拟抢购件数
                        "skuStock": sku.skuStock,//库存
                        "skuCurrentPrice": sku.skuCurrentPrice ? sku.skuCurrentPrice : 0,//日常价格
                    }
                    if (mode === 'edit') {
                        t.goodsSurplusSum = sku.goodsSurplusSum
                    }
                    return t
                })
            }
        })
    }
    const setTData = (v) => {
        formRef.current.setFieldsValue({
            goodList: transData(v)
        })
        // setTableData(v)
    }
    const formItemLayout = {
        labelCol: {span: 2},
        wrapperCol: {span: 22},
    }
    return (
        <div className={'wrap-box'}>
            <GoBack title={title}/>
            <div className={'wrap-box-content'}>
                <ProForm
                    {...formItemLayout}
                    formRef={formRef}
                    readonly={mode === "view"}
                    layout={'horizontal'}
                    submitter={{
                        render: (props, doms) => {
                            return mode === "view" ? null :
                                <Row>
                                    <Col span={22} offset={2}>
                                        <Space>{doms}</Space>
                                    </Col>
                                </Row>
                        },
                    }}
                    // onValuesChange={(changeValues) => console.log(changeValues)}
                    onFinish={async (values) => {
                        // await onFinish(values)
                        if (mode === "add") {
                            await apiSeckillActivityAdd({...values, floorPrice: true}).then((res) => {
                                if (res.code === 0) {
                                    message.success('提交成功');
                                    navigate(-1)
                                }
                            })
                        } else {
                            await apiSeckillActivityEdit({activityId: location.state.activityId, ...values, floorPrice: true}).then(res => {
                                if (res.code === 0) {
                                    message.success('提交成功');
                                    navigate(-1)
                                }
                            })
                        }
                    }}
                    onFinishFailed={(values) => {
                        if (values.errorFields.length) {
                            message.error('请完善数据')
                        }
                    }}
                    params={{}}
                    request={async () => {
                        // await waitTime(100);
                        // 判断当前页面类型
                        if (mode === 'add') {
                            return {}
                        } else {
                            // 跑接口取回显数据
                            let res = await apiSeckillActivityDetail({
                                activityId: location.state.activityId,
                                activityType: location.state.activityType
                            })
                            if (res.code === 0 && res.data) {
                                res.data.activityTime = [res.data.warmingTime, res.data.endTime]
                                if (res.data.enabledDecrement === 0) {
                                    res.data.types = ['enabledDecrement', 'enabledDeliver']
                                }
                                return res.data
                            }
                        }
                    }}
                >
                    <ProFormSelect
                        width="md"
                        name="activityType"
                        label="活动类型"
                        options={options}
                        disabled={mode === 'edit'}
                        rules={[{required: true, message: '请选择活动类型'}]}
                    />
                    <ProFormText
                        width="md"
                        name="activityName"
                        label="活动名称"
                        fieldProps={{
                            showCount: true,
                            maxLength: 50
                        }}
                        rules={[{required: true, message: '请输入活动名称'}]}
                    />
                    <ProFormDateTimeRangePicker
                        width="md"
                        name={'activityTime'}
                        label="活动时间"
                        showTime={
                            {format: 'HH:mm',}
                        }
                        fieldProps={{
                            // format: (value) => value.format(format),
                            format: "YYYY-MM-DD HH:mm"
                        }}
                        transform={(values) => {
                            return {
                                warmingTime: values ? values[0] : undefined,
                                endTime: values ? values[1] : undefined,
                            };
                        }}
                        rules={[
                            {
                                required: true,
                                validator: (_, value) => {
                                    if (value) {
                                        let a = moment(new Date()).format(format);
                                        let b = null;
                                        if (typeof value[1] === 'string' || value[1] instanceof String) {
                                            b = moment(value[1]).format('YYYY-MM-DD HH:mm');
                                        } else {
                                            b = value[1].format('YYYY-MM-DD HH:mm');
                                        }
                                        if (moment(a).isBefore(b)) {
                                            return Promise.resolve();
                                        }
                                        return Promise.reject(new Error('请选择未来的时间范围'));
                                    } else {
                                        return Promise.reject(new Error('请选择活动时间'));
                                    }
                                },
                            }
                        ]}
                    />
                    <ProFormDateTimePicker
                        width="md"
                        name={'startTime'}
                        label="秒杀开始"
                        dependencies={['activityTime']}
                        showTime={
                            {format: 'HH:mm',}
                        }
                        fieldProps={{
                            // format: (value) => value.format(format),
                            format: "YYYY-MM-DD HH:mm"
                        }}
                        rules={[
                            ({getFieldValue}) => ({
                                required: true,
                                validator(_, value) {
                                    if (value) {
                                        let regex = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/;
                                        let sTime, eTime, startTime
                                        if (regex.test(getFieldValue('activityTime')[0])) {
                                            sTime = getFieldValue('activityTime')[0];
                                            eTime = getFieldValue('activityTime')[1];
                                        } else {
                                            sTime = getFieldValue('activityTime')[0].format(format);
                                            eTime = getFieldValue('activityTime')[1].format(format);
                                        }
                                        if (regex.test(value)) {
                                            startTime = value
                                        } else {
                                            startTime = value.format(format)
                                        }
                                        if (moment(startTime).isBetween(sTime, eTime, null, '[]')) {
                                            return Promise.resolve();
                                        }
                                        return Promise.reject(new Error('秒杀开始时间必须在活动开始时间和结束时间范围内'));
                                    } else {
                                        return Promise.reject(new Error('请选择秒杀时间'));
                                    }
                                },
                            }),
                        ]}
                    />
                    <ProFormCheckbox.Group
                        label="优惠叠加"
                        name="types"
                        initialValue={['enabledDeliver']}
                        // rules={[{ required: true }]}
                        transform={(values) => {
                            return {
                                enabledDecrement: values ? (values.includes('enabledDecrement') ? 0 : 1) : undefined,
                                enabledDeliver: values ? (values.includes('enabledDeliver') ? 0 : 1) : undefined,
                                couponEnabled: values ? (values.includes('couponEnabled') ? 0 : 1) : undefined,
                            };
                        }}
                        options={[
                            {
                                label: '全平台满减',
                                value: 'enabledDecrement',
                            },
                            {
                                label: '全平台满赠',
                                value: 'enabledDeliver',
                                disabled: true
                            },
                            {
                                label: '优惠券',
                                value: 'couponEnabled',
                                disabled: true
                            },
                        ]}
                    />
                    <ProForm.Item
                        label="商品"
                        name="goodList"
                        trigger="onValuesChange"
                        rules={
                            [
                                {
                                    required: true,
                                    message: ""
                                },
                                ({getFieldValue}) => ({
                                    validator(_, value) {
                                        if (value.length < (getFieldValue('activityType') === 'SECKILL_ACTIVITY' ? 1 : 3)) {
                                            return Promise.reject(new Error(`请至少选择${getFieldValue('activityType') === 'SECKILL_ACTIVITY' ? 1 : 3}个商品`));
                                        }
                                        return Promise.resolve();
                                    },
                                }),
                            ]
                        }
                        convertValue={(value) => {
                            if (value) {
                                return convertData(value)
                            } else return []
                        }}
                    >
                        <Goods mode={mode} set={setTData} activityId={activityId} formRef={formRef}
                               isProprietary={isProprietary}/>
                    </ProForm.Item>
                </ProForm>
            </div>
        </div>
    )
};
export default Add;
